
#include "dymem.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>


#define tc_log(_fmt_, ...)          printf("[TC][%s:%d][%s] "_fmt_"\r\n", __FILE__, __LINE__, __func__, ##__VA_ARGS__)
#define tc_log_err(_fmt_, ...)      printf("[TC][ERR][%s:%d][%s] "_fmt_"\r\n", __FILE__, __LINE__, __func__, ##__VA_ARGS__)


#define HEAP_LENGTH		512


static void hex_dump(char *desc, unsigned char *data, int len)
{
    unsigned int i;

    printf("%s size %d hex dump:", desc, len);
    for(i=0; i<len; i++)
    {
        if (i % 16 == 0)
            printf("\n0x%p: ", &data[i]);

        printf(" %02x", data[i]);
    }
    printf("\n");
}

int main()
{
	int i, j;
	dymem_obj_t h_pool;
	unsigned char *buffer1 = NULL, *buffer2 = NULL;

	u8* heap = malloc(HEAP_LENGTH);
	memset(heap, 0x0, HEAP_LENGTH);

	dymem_heap_init(&h_pool, heap, heap + HEAP_LENGTH);
	hex_dump("step0", heap, HEAP_LENGTH);
	dymem_list(&h_pool);

	for (j=0; j<2; j++)
	{
		tc_log("malloc 100 space for buffer1");
		buffer1 = dymem_malloc(&h_pool, 100);
		if(buffer1 == NULL) 
		{
			tc_log_err("buffer1 is NULL");
			goto err;
		}
		for(i=0; i<100; i++)
			buffer1[i] = i + 1;

		hex_dump("step1", heap, HEAP_LENGTH);
		dymem_list(&h_pool);


		tc_log("malloc 100 space for buffer2");
		buffer2 = dymem_malloc(&h_pool, 100);
		if(buffer2 == NULL) 
		{
			tc_log_err("buffer2 is NULL");
			goto err;
		}
		for(i=0; i<100; i++)
			buffer2[i] = i + 1;

		hex_dump("step2", heap, HEAP_LENGTH);
		dymem_list(&h_pool);

err:
		if (buffer2 != NULL)
			dymem_free(&h_pool, buffer2);

		hex_dump("step3", heap, HEAP_LENGTH);
		dymem_list(&h_pool);

		if (buffer1 != NULL)
			dymem_free(&h_pool, buffer1);

		hex_dump("step4", heap, HEAP_LENGTH);
		dymem_list(&h_pool);
	}

	free(heap);
	return 0;
}

